#include <func.h>
// gcc getAbsolutePathId.c -o exec -lmysqlclient

int getAbsolutePathId(int id_now, const char* path, const char* username, MYSQL * mysql) {
    char sql[4096] = {0};
    char path_usr[4096] = {0};
    strcpy(path_usr, path);
    if (strlen(path_usr) == 0) {
        return id_now;
    }

    if (path_usr[0] == '/') {
        id_now = 1;
    }
    char *token;
    char delim[] = "/";
    token = strtok(path_usr, delim);

    while (token != NULL) {

        if (strcmp(token, "..") == 0) {
            bzero(sql, sizeof(sql));
            strcpy(sql, "select pre_id from virtual_file where user = '");
            strcat(sql, username);
            strcat(sql, "' and id = ");
            char str[20] = {0};
            sprintf(str,"%d",id_now);
            
            strcat(sql,str);
            strcat(sql,";");
            int qret = mysql_query(mysql,sql);
            if(qret != 0){
                fprintf(stderr,"error 2:%s\n", mysql_error(mysql));
                return -1;
            }
            MYSQL_RES *res = mysql_store_result(mysql);
            MYSQL_ROW row;
            row = mysql_fetch_row(res);
            int resu = atoi(row[0]);
            if (resu != -1) {
                id_now = resu;
            }
        } else if (strcmp(token, ".") == 0) {
        } else {
            bzero(sql, sizeof(sql));
            strcpy(sql, "select id from virtual_file where user = '");
            strcat(sql, username);
            strcat(sql, "' and pre_id = ");
            char str[20] = {0};
            sprintf(str,"%d",id_now);
            strcat(sql,str);
            strcat(sql, " and name = '");
            strcat(sql, token);
            strcat(sql,"';");

            mysql_query(mysql,sql); 
            MYSQL_RES *res = mysql_store_result(mysql);
            unsigned long rows_res = mysql_num_rows(res);
            if (rows_res == (unsigned long)0) {
                return -1;
            } else {
                MYSQL_ROW row;
                row = mysql_fetch_row(res);
                int resu = atoi(row[0]);
                id_now = resu;
            }
        }
        token = strtok(NULL, delim);
    }
    return id_now;
}